package org.xxpay.manage.config.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayInterface;
import org.xxpay.core.entity.PayInterfaceType;
import org.xxpay.core.entity.PayPassage;
import org.xxpay.manage.common.ctrl.BaseController;
import org.xxpay.manage.common.service.CommonService;
import org.xxpay.manage.config.service.CommonConfigService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author: dingzhiwei
 * @date: 18/05/04
 * @description: 支付通道
 */
@RestController
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/config/pay_passage")
public class PayPassageController extends BaseController {

    @Autowired
    private CommonConfigService commonConfigService;

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        PayPassage payPassage = getObject(param, PayPassage.class);
        payPassage.setBelongInfoType(MchConstant.SYSTYPE_MGR);
        int count = commonService.payPassageService.count(payPassage);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<PayPassage> payPassageList = commonService.payPassageService.select((getPageIndex(param) -1) * getPageSize(param), getPageSize(param), payPassage);
        // 支付接口类型Map
        Map payInterfaceTypeMap = commonConfigService.getPayInterfaceTypeMap();
        // 支付接口Map
        Map payInterfaceMap = commonConfigService.getPayInterfaceMap();
        // 支付类型Map
        Map payTypeMap = commonConfigService.getPayTypeMap();

        // 转换前端显示
        List<JSONObject> objects = new LinkedList<>();
        for(PayPassage info : payPassageList) {
            JSONObject object = (JSONObject) JSON.toJSON(info);
            object.put("payTypeName", payTypeMap.get(info.getPayType()));               // 转换支付类型名称
            object.put("ifTypeName", payInterfaceTypeMap.get(info.getIfTypeCode()));    // 转换接口类型名称
            object.put("ifName", payInterfaceMap.get(info.getIfCode()));                // 转换支付接口名称
            objects.add(object);
        }
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(objects, count));
    }

    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer id = getIntegerRequired(param, "id");
        PayPassage payPassage = commonService.payPassageService.findById(id);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(payPassage));
    }

    @RequestMapping("/update")
    @ResponseBody
    @MethodLog( remark = "修改支付通道" )
    public ResponseEntity<?> update(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        PayPassage payPassage = getObject(param, PayPassage.class);
        String ifCode = payPassage.getIfCode();
        PayInterface payInterface = commonService.payInterfaceService.findByCode(ifCode);
        if(payInterface == null) {
            return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_MGR_PAY_INTERFACE_NOT_EXIST));
        }
        payPassage.setIfTypeCode(payInterface.getIfTypeCode()); // 设置支付接口类型

        int count = commonService.payPassageService.update(payPassage);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    @RequestMapping("/risk_update")
    @ResponseBody
    @MethodLog( remark = "修改支付通道风控" )
    public ResponseEntity<?> updateRisk(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        param.replace("maxDayAmount",StringUtils.deleteWhitespace(param.getString("maxDayAmount")));
        param.replace("maxEveryAmount",StringUtils.deleteWhitespace(param.getString("maxEveryAmount")));
        param.replace("minEveryAmount",StringUtils.deleteWhitespace(param.getString("minEveryAmount")));
        handleParamAmount(param, "maxDayAmount", "maxEveryAmount", "minEveryAmount");
        PayPassage payPassage = getObject(param, PayPassage.class);
        int count = commonService.payPassageService.update(payPassage);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    @RequestMapping("/rate_update")
    @ResponseBody
    @MethodLog( remark = "修改支付通道费率" )
    public ResponseEntity<?> updateRate(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer id = getIntegerRequired(param, "id");
        String passageRate = StringUtils.deleteWhitespace(getStringRequired(param, "passageRate"));
        PayPassage payPassage = new PayPassage();
        payPassage.setId(id);
        payPassage.setPassageRate(new BigDecimal(passageRate));
        int count = commonService.payPassageService.updateRate(payPassage);
        if(count >= 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    @RequestMapping("/add")
    @ResponseBody
    @MethodLog( remark = "新增支付通道" )
    public ResponseEntity<?> add(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        param.replace("passageRate",StringUtils.deleteWhitespace(param.getString("passageRate")));
        PayPassage payPassage = getObject(param, PayPassage.class);
        payPassage.setBelongInfoType(MchConstant.SYSTYPE_MGR);
        payPassage.setBelongInfoId(0L);
        String ifCode = payPassage.getIfCode();
        PayInterface payInterface = commonService.payInterfaceService.findByCode(ifCode);
        if(payInterface == null) {
            return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_MGR_PAY_INTERFACE_NOT_EXIST));
        }
        payPassage.setIfTypeCode(payInterface.getIfTypeCode()); // 设置支付接口类型
        int count = commonService.payPassageService.add(payPassage);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    /**
     * 根据支付通道ID,获取支付账号配置定义描述
     * @param request
     * @return
     */
    @RequestMapping("/pay_config_get")
    @ResponseBody
    public ResponseEntity<?> getPayConfig(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer payPassageId = getIntegerRequired(param, "payPassageId");
        PayPassage payPassage = commonService.payPassageService.findById(payPassageId);
        if(payPassage == null) {
            return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_RECORD_NOT_EXIST));
        }
        String ifCode = payPassage.getIfCode();
        String ifTypeCode = payPassage.getIfTypeCode();

        // 如果接口配置了定义描述,则使用接口
        PayInterface payInterface = commonService.payInterfaceService.findByCode(ifCode);
        if(payInterface != null && StringUtils.isNotBlank(payInterface.getParam())) {
            // 支付接口类型Map
            Map payInterfaceTypeMap = commonConfigService.getPayInterfaceTypeMap();
            JSONObject object = (JSONObject) JSON.toJSON(payInterface);
            object.put("ifTypeName", payInterfaceTypeMap.get(payInterface.getIfTypeCode()));
            return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
        }
        // 使用接口类型配置的定义描述
        PayInterfaceType payInterfaceType = commonService.payInterfaceTypeService.findByCode(ifTypeCode);
        if(payInterfaceType != null && StringUtils.isNotBlank(payInterfaceType.getParam())) {
            // 支付接口类型Map
            Map payInterfaceTypeMap = commonConfigService.getPayInterfaceTypeMap();
            JSONObject object = (JSONObject) JSON.toJSON(payInterfaceType);
            object.put("ifTypeName", payInterfaceTypeMap.get(payInterfaceType.getIfTypeCode()));
            return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
        }
        return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_RECORD_NOT_EXIST));
    }


    @RequestMapping("/relationDelete")
    @ResponseBody
    @MethodLog( remark = "彻底删除支付通道" )
    public ResponseEntity<?> delAccount(String ids, String superPassword) {
//        checkSecurityReq(null);  //敏感操作，用户安全认证校验

        if(!checkMgrSuperPwd(superPassword)) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MGR_SUPER_PASSWORD_NOT_MATCH));
        }
        //验证删除开关是否打开
        DBApplicationConfig config = getDBApplicationConfig();
        if (config.getCleanFlag() != MchConstant.PUB_YES) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MGR_DATA_CLEAN_FLAG_OFF));
        }

        List<Integer> idsLong = JSON.parseArray(ids, Integer.class);
        int delNum = commonService.payPassageService.relationDelete(idsLong);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(delNum));
    }

    @RequestMapping("/updateStatus")
    @ResponseBody
    @MethodLog( remark = "修改支付通道状态" )
    public ResponseEntity<?> updateStatus(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer id = getInteger(param, "id");
        Byte status = getByte(param, "status");
        PayPassage payPassage = new PayPassage();
        payPassage.setStatus(status);
        payPassage.setId(id);
        int count = commonService.payPassageService.update(payPassage);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }
}
